"""
coding:utf-8
@describe:创建视图函数文件
@Time:2022/5/28 21:38
@Author:川
"""
import logging
import os

from flask import Blueprint, request, jsonify

from apps.pymysql.base import SQLManager

# 蓝图名称api_demo
api_demo = Blueprint('demo', __name__)


@api_demo.get('/')
def hello_world():  # 函数名不要和蓝图名api_demo重复
    logging.error("开心就好error!")
    logging.debug("debug无言!")
    logging.info("info详情!")
    logging.warning("warning开心!")
    logging.error("错误提示日志")
    logging.critical("123错误提示日志")
    return jsonify(code=200, msg='您好, 欢迎入手Flask66')

@api_demo.get('/tests/')
def tests():  # 函数名不要和蓝图名api_demo重复
    sql1 = "select * from test"
    sql2 = "INSERT INTO `flask`.`test`(`name`) VALUES ('悲伤99')"
    sql3 = "INSERT INTO `flask`.`test`(`name`) VALUES ('悲伤99')"
    db = SQLManager()
    result = db.many_sql([sql2, sql3])
    db = SQLManager()
    data = db.get(sql1)
    return jsonify(code=200, msg='您好, 欢迎入手Flask', data=result, result=data)


@api_demo.route('/upload/', methods=["POST"])
def upload():
    """接受前端传送过来的文件"""
    fileObj = request.files.get("file")
    if fileObj is None:
        return jsonify(code=422, msg='file文件信息不能为空')
    # 直接使用文件上传对象保存
    file_name = fileObj.filename
    #   确保文件扩展名是允许的
    #   os.path.splitext() 函数将文件名和扩展名分开
    file_ext = os.path.splitext(file_name)[1]
    if file_ext not in ['.jpg', '.png']:
        return jsonify(code=422, msg='当前文件扩展名是:%s,只允许上传.jpg和.png结尾的文件' % file_ext)
    folder = './test/test/'
    os.makedirs(folder, mode=0o755, exist_ok=True)
    path = "%s%s" % (folder, file_name)
    fileObj.save(path)
    return jsonify(code=200, msg='上传成功', data={"path": path})